package service

import (
	"SkyPath/internal/domain/project/constant"
	"SkyPath/internal/infrastructure"
	implProjects "SkyPath/internal/infrastructure/gatewayimpl/project"
	"database/sql"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

/*
具体业务代码实现
*/
type Projects struct{}

// 创建省级项目
func (pj *Projects) CreateProjects(project constant.Projects) error {
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()
	projectsStruct := implProjects.Projects{
		ProjectName:        project.ProjectName,
		ProjectID:          project.ProjectID,
		ProjectDescription: project.ProjectDescription,
		ProjectStatus:      project.ProjectStatus,
		ProjectVisible:     project.ProjectVisible,
		ProjectFlag:        project.ProjectFlag,
		ProjectStartTime:   project.ProjectStartTime,
		ProjectEndTime:     project.ProjectEndTime,
		ProjectManagerId:   project.ProjectManagerId,
		ProjectMemberId:    project.ProjectMemberId,
		ProjectCreateTime:  project.ProjectCreateTime,
		ProjectUpdateTime:  project.ProjectUpdateTime,
	}
	err := infs.Exec(&projectsStruct)
	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

// 插入条目信息
func (pj *Projects) CreateProjectItems(items constant.ProjectItems) error {
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()

	projectItemsInfo := implProjects.ProjectItemsInfo{
		ProjectID:      items.ProjectID,
		ProjectItemsId: items.ProjectItemsId,
		SystemName:     items.SystemName,
		IssueCount:     strconv.Itoa(strings.Count(items.Issue, "\n\t")),
		ReformStatus:   items.ReformStatus,
	}
	err := infs.SaveOrUpdate(&projectItemsInfo, []string{"project_items_id"}, []string{"project_id",
		"project_items_id", "system_name", "issue_count", "reform_status"})

	//err = infs.Exec(&ProjectItemsInfo)
	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}

	//issueList := strings.Split(items.Issue, ",")
	//for _, issue := range issueList{
	projectItemsPlan := implProjects.ProjectItemsPlan{
		ProjectItemsId:                items.ProjectItemsId,
		Issue:                         items.Issue,
		SystemSurveyExcel:             items.SystemSurveyExcel,
		ExpectBeOnlineTime:            items.ExpectBeOnlineTime,
		ExpectBeSimulateTime:          items.ExpectBeSimulateTime,
		ClusterDeployStatus:           items.ClusterDeployStatus,
		CompatibleChange:              items.CompatibleChange,
		SpecialVersionLimit:           items.SpecialVersionLimit,
		GUCParamCheck:                 items.GUCParamCheck,
		LicenseCheck:                  items.LicenseCheck,
		WhiteListConfiguration:        items.WhiteListConfiguration,
		ArchiveAndBackupConfiguration: items.ArchiveAndBackupConfiguration,
		ServerAndDBMonitor:            items.ServerAndDBMonitor,
		DiskAndIOAndCPUCheck:          items.DiskAndIOAndCPUCheck,
		MigrateTest:                   items.MigrateTest,
		DeployConfirmForm:             items.DeployConfirmForm,
		DeployConfirmFormPath:         getDeployConfirmFormPath(),
	}
	//}
	err = infs.SaveOrUpdate(&projectItemsPlan, []string{"project_items_id"}, []string{"project_items_id",
		"issue", "system_survey_excel", "expect_be_online_time", "expect_be_simulate_time", "cluster_deploy_status",
		"compatible_change", "special_version_limit", "guc_param_check", "license_check", "white_list_configuration",
		"archive_and_backup_configuration", "server_and_db_monitor", "disk_and_io_and_cpu_check", "migrate_test"})
	//err = infs.Exec(&ProjectItemsPlan)
	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}

	// 台账信息表
	projectLedger := implProjects.Ledger{
		ProjectItemsId:          items.Ledger.ProjectItemsId,
		TicketYears:             items.Ledger.TicketYears,
		ProjectManager:          items.Ledger.ProjectManager,
		ProjectRoleA:            items.Ledger.ProjectRoleA,
		OfficialManager:         items.Ledger.OfficialManager,
		TicketInfo:              items.Ledger.TicketInfo,
		ProjectStatus:           items.Ledger.ProjectStatus,
		ProgressStream:          items.Ledger.ProgressStream,
		ExpectDeployTime:        items.Ledger.ExpectDeployTime,
		ProjectReplyOnlineTime:  items.Ledger.ProjectReplyOnlineTime,
		Env:                     items.Ledger.Env,
		ServerHandover:          items.Ledger.ServerHandover,
		Migrate:                 items.Ledger.Migrate,
		ExpectOnlineTime:        items.Ledger.ExpectOnlineTime,
		BelongCompany:           items.Ledger.BelongCompany,
		BelongApartment:         items.Ledger.BelongApartment,
		BelongBusiness:          items.Ledger.BelongBusiness,
		SubSystemName:           items.Ledger.SubSystemName,
		BussinessLevel:          items.Ledger.BussinessLevel,
		MainUses:                items.Ledger.MainUses,
		ProjectBussinessManager: items.Ledger.ProjectBussinessManager,
		ContactPhoneNumber:      items.Ledger.ContactPhoneNumber,
		LoginType:               items.Ledger.LoginType,
		UserAndPasswd:           items.Ledger.UserAndPasswd,
		Remarks:                 items.Ledger.Remarks,
	}
	err = infs.SaveOrUpdate(&projectLedger,
		[]string{"project_items_id"},
		[]string{"project_items_id", "ticket_years", "project_manager", "project_role_a", "official_manager", "ticket_info",
			"project_status", "progress_stream", "expect_deloy_time", "project_reply_online_time", "env", "server_handover",
			"migrate", "expect_online_time", "belong_company", "belong_apartment", "belong_business", "sub_system_name", "bussiness_level",
			"main_uses", "project_bussiness_manager", "contact_phone_number", "login_type", "user_and_passwd", "remarks"})
	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}

	// 服务器信息表
	projectServerInfo := implProjects.ServerInfo{
		ProjectItemsId:  items.ProjectItemsId,
		ServerType:      items.ServerInfo.ServerType,
		ServerStructure: items.ServerInfo.ServerStructure,
		OsName:          items.ServerInfo.OsName,
		CpuStructure:    items.ServerInfo.CpuStructure,
		CpuInfo:         items.ServerInfo.CpuInfo,
		CpuCoreCount:    items.ServerInfo.CpuCoreCount,
		OsPlantform:     items.ServerInfo.OsPlantform,
		OsVersion:       items.ServerInfo.OsVersion,
		OsCoreVersion:   items.ServerInfo.OsCoreVersion,
		MemoryInfo:      items.ServerInfo.MemoryInfo,
		DiskInfo:        items.ServerInfo.DiskInfo,
		Structure:       items.ServerInfo.Structure,
		ClusterName:     items.ServerInfo.ClusterName,
		HostName:        items.ServerInfo.HostName,
		Domain:          items.ServerInfo.Domain,
		Pod:             items.ServerInfo.Pod,
	}

	err = infs.SaveOrUpdate(&projectServerInfo, []string{"project_items_id"}, []string{
		"server_type", "server_structure", "os_name", "cpu_structure", "cpu_info",
		"cpu_core_count", "os_plantform", "os_version", "os_core_version", "memory_info",
		"disk_info", "structure", "cluster_name", "host_name", "domain", "pod"})
	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}

	// 数据库信息表
	projectDatabaseInfo := implProjects.DatabaseInfo{
		ProjectItemsId:   items.ProjectItemsId,
		DataVolume:       items.DatabaseInfo.DataVolume,
		DbType:           items.DatabaseInfo.DbType,
		DbVersion:        items.DatabaseInfo.DbVersion,
		CompatibleModel:  items.DatabaseInfo.CompatibleModel,
		DbIp:             items.DatabaseInfo.DataVolume,
		DbVip:            items.DatabaseInfo.DbVip,
		DbPort:           items.DatabaseInfo.DbPort,
		DbDataPath:       items.DatabaseInfo.DbDataPath,
		DbArchivePath:    items.DatabaseInfo.DbArchivePath,
		DbBackupPath:     items.DatabaseInfo.DbBackupPath,
		DbBackupStrategy: items.DatabaseInfo.DbBackupStrategy,
		Monitor:          items.DatabaseInfo.Monitor,
	}
	err = infs.SaveOrUpdate(&projectDatabaseInfo, []string{"project_items_id"}, []string{
		"data_volume", "db_type", "db_version", "compatible_model", "db_ip", "db_vip",
		"db_port", "db_data_path", "db_archive_path", "db_backup_path",
		"db_backup_strategy", "monitor"})
	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}

	return nil

}

// 获取省级项目，或者获取某个省级项目，或者获取某几个省级项目
func (pj *Projects) GetProjects(project constant.Projects) ([]interface{}, error) {
	var sqlStr string
	if project.ProjectID == "0" {
		sqlStr = "select * from Projects"
	} else if (strings.Count(project.ProjectID, ",")) == 0 && project.ProjectID != "0" {
		// 获取单个省的信息
		sqlStr = "select * from Projects where ProjectID = '" + project.ProjectID + "'"
	} else {
		// 获取某几个省的信息
		sqlStr = "select * from Projects where ProjectID in (" + project.ProjectID + ")"
	}
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()
	rows := infs.Query(sqlStr)
	rowsVal, err := pj.fetchRows(rows)
	return rowsVal, err
}

func (pj *Projects) fetchRows(rows *sql.Rows) ([]interface{}, error) {

	// 获取列名
	columns, err := rows.Columns()
	if err != nil {
		log.Fatal(err)
		return nil, err
	}
	columnCount := len(columns)
	var rowResult []interface{}
	for rows.Next() {
		row := make([]interface{}, columnCount)

		scanArgs := make([]interface{}, columnCount)
		for i := range row {
			scanArgs[i] = &row[i]
		}

		err := rows.Scan(scanArgs...)
		if err != nil {
			log.Fatal(err)
			return nil, err
		}

		for i, v := range row {
			if b, ok := v.([]byte); ok {
				row[i] = string(b)
			}
		}
		rowResult = append(rowResult, row)
	}
	return rowResult, nil
}

// 获取省级项目下的条目，0为所有条目，如果字符串中未包含了逗号并且不为0，那么应该是获取单个条目，其他则获取指定条目
func (pj *Projects) GetProjectItems(items constant.ProjectItems) ([]interface{}, error) {
	var sqlStr string
	if items.ProjectItemsId == "0" {
		sqlStr = "select * from project_items_infos"
	} else if (strings.Count(items.ProjectItemsId, ",")) == 0 && items.ProjectItemsId != "0" {
		// 获取单个省的信息
		sqlStr = "select * from project_items_infos where project_items_id = '" + items.ProjectItemsId + "'"
	} else {
		// 获取某几个省的信息
		sqlStr = "select * from project_items_infos where project_items_id in (" + items.ProjectItemsId + ")"
	}
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()
	rows := infs.Query(sqlStr)
	rowsVal, err := pj.fetchRows(rows)
	return rowsVal, err
}

// 获取省级项目下的条目想起信息，0为所有条目，如果字符串中未包含了逗号并且不为0，那么应该是获取单个条目，其他则获取指定条目
func (pj *Projects) GetProjectItemsDetail(items constant.ProjectItems) ([]interface{}, error) {
	var sqlStr string
	if items.ProjectItemsId == "0" {
		sqlStr = "select * from project_items_plans"
	} else if (strings.Count(items.ProjectItemsId, ",")) == 0 && items.ProjectItemsId != "0" {
		sqlStr = "select * from project_items_plans where project_items_id = '" + items.ProjectItemsId + "'"
	} else {
		sqlStr = "select * from project_items_plans where project_items_id in (" + items.ProjectItemsId + ")"
	}
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()
	rows := infs.Query(sqlStr)
	rowsVal, err := pj.fetchRows(rows)
	return rowsVal, err
}

// 删除省级项目
func (pj *Projects) DelProjects(project constant.Projects) error {
	var sqlStr string
	if project.ProjectID == "0" {
		sqlStr = "delete from Projects"
	} else if (strings.Count(project.ProjectID, ",")) == 0 && project.ProjectID != "0" {
		// 获取单个省的信息
		sqlStr = "select * from Projects where ProjectID = '" + project.ProjectID + "'"
	} else {
		// 获取某几个省的信息
		sqlStr = "select * from Projects where ProjectID in (" + project.ProjectID + ")"
	}
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()
	err := infs.Exec(sqlStr)
	if err != nil {
		return err
	}

	return nil
}

// 删除省级项目
func (pj *Projects) DelProjectItems(items constant.ProjectItems) error {
	var sqlStr string
	if items.ProjectItemsId == "0" {
		sqlStr = "delete from Projects"
	} else if (strings.Count(items.ProjectItemsId, ",")) == 0 && items.ProjectItemsId != "0" {
		// 获取单个省的信息
		sqlStr = "select * from Projects where ProjectID = '" + items.ProjectItemsId + "'"
	} else {
		// 获取某几个省的信息
		sqlStr = "select * from Projects where ProjectID in (" + items.ProjectItemsId + ")"
	}
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()
	err := infs.Exec(sqlStr)
	if err != nil {
		return err
	}

	return nil
}

// 更改省级项目
func (pj *Projects) ChangeProjects(project constant.Projects) error {
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()

	Projects := implProjects.Projects{
		ProjectName:        project.ProjectName,
		ProjectID:          project.ProjectID,
		ProjectDescription: project.ProjectDescription,
		ProjectStatus:      project.ProjectStatus,
		ProjectVisible:     project.ProjectVisible,
		ProjectFlag:        project.ProjectFlag,
		ProjectStartTime:   project.ProjectStartTime,
		ProjectEndTime:     project.ProjectEndTime,
		ProjectManagerId:   project.ProjectManagerId,
		ProjectMemberId:    project.ProjectMemberId,
		ProjectCreateTime:  project.ProjectCreateTime,
		ProjectUpdateTime:  project.ProjectUpdateTime,
	}
	err := infs.SaveOrUpdate(&Projects, []string{"project_name", "project_id"}, []string{"project_name",
		"project_id", "project_description", "project_status", "project_visible", "project_flag",
		"project_start_time", "project_end_time", "project_manager_id", "project_member_id", "project_create_time",
		"project_update_time"})

	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}

	return nil
}

// 更改省级项目下某个条目信息
func (pj *Projects) ChangeProjectItems(items constant.ProjectItems) error {
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()

	ProjectItemsInfo := implProjects.ProjectItemsInfo{
		ProjectID:      items.ProjectID,
		ProjectItemsId: items.ProjectItemsId,
		SystemName:     items.SystemName,
		IssueCount:     strconv.Itoa(strings.Count(items.Issue, "\n\t")),
		ReformStatus:   items.ReformStatus,
	}
	err := infs.SaveOrUpdate(&ProjectItemsInfo, []string{"project_items_id"}, []string{"project_id",
		"project_items_id", "system_name", "issue_count", "reform_status"})

	//err = infs.Exec(&ProjectItemsInfo)
	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}

	//issueList := strings.Split(items.Issue, ",")
	//for _, issue := range issueList{
	ProjectItemsPlan := implProjects.ProjectItemsPlan{
		ProjectItemsId:                items.ProjectItemsId,
		Issue:                         items.Issue,
		SystemSurveyExcel:             items.SystemSurveyExcel,
		ExpectBeOnlineTime:            items.ExpectBeOnlineTime,
		ExpectBeSimulateTime:          items.ExpectBeSimulateTime,
		ClusterDeployStatus:           items.ClusterDeployStatus,
		CompatibleChange:              items.CompatibleChange,
		SpecialVersionLimit:           items.SpecialVersionLimit,
		GUCParamCheck:                 items.GUCParamCheck,
		LicenseCheck:                  items.LicenseCheck,
		WhiteListConfiguration:        items.WhiteListConfiguration,
		ArchiveAndBackupConfiguration: items.ArchiveAndBackupConfiguration,
		ServerAndDBMonitor:            items.ServerAndDBMonitor,
		DiskAndIOAndCPUCheck:          items.DiskAndIOAndCPUCheck,
		MigrateTest:                   items.MigrateTest,
		DeployConfirmForm:             items.DeployConfirmForm,
		DeployConfirmFormPath:         getDeployConfirmFormPath(),
	}
	//}
	err = infs.SaveOrUpdate(&ProjectItemsPlan, []string{"project_items_id"}, []string{"project_items_id",
		"issue", "system_survey_excel", "expect_be_online_time", "expect_be_simulate_time", "cluster_deploy_status",
		"compatible_change", "special_version_limit", "guc_param_check", "license_check", "white_list_configuration",
		"archive_and_backup_configuration", "server_and_db_monitor", "disk_and_io_and_cpu_check", "migrate_test"})
	//err = infs.Exec(&ProjectItemsPlan)
	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}

	return nil
}

// 获取台账列表
func (pj *Projects) GetLedgers() ([]interface{}, error) {
	sqlStr := `SELECT 
  				ticket_years, project_manager, project_role_a, official_manager, ticket_info, project_status, progress_stream,
  				expect_deploy_time, project_reply_online_time, server_type, server_structure, os_name, cpu_structure, cpu_info,
  				cpu_core_count, os_plantform, os_version, os_core_version, memory_info, disk_info, structure, cluster_name,
  				host_name, domain, pod, data_volume, db_type, db_version, compatible_model, db_ip, db_vip, db_port,
  				db_data_path, db_archive_path, db_backup_path, db_backup_strategy, monitor, env, server_handover, migrate,
  				expect_online_time, belong_company, belong_apartment, belong_business, sub_system_name, bussiness_level, main_uses,
  				project_bussiness_manager, contact_phone_number, login_type, user_and_passwd, remarks, project_items_id
				FROM ledgers`
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()
	rows := infs.Query(sqlStr)
	rowsVal, err := pj.fetchRows(rows)
	return rowsVal, err
}

// 获取台账表头
func (pj *Projects) GetLedgerHeaders() ([]interface{}, error) {
	sqlStr := `SELECT
	a.attname AS column_name,
	d.description AS column_comment
	FROM
	pg_class c
	JOIN pg_attribute a ON a.attrelid = c.oid
	LEFT JOIN pg_description d ON d.objoid = c.oid AND d.objsubid = a.attnum
	WHERE
	c.relname = 'ledgers'
	AND c.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')
	AND a.attnum > 0
	AND NOT a.attisdropped AND a.attname not in ('id', 'created_at', 'updated_at', 'deleted_at')`
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()
	rows := infs.Query(sqlStr)
	rowsVal, err := pj.fetchRows(rows)
	return rowsVal, err
}

func (pj *Projects) ChangeLedgers(ledger map[string]interface{}) error {
	fmt.Println(ledger["ticket_years"])
	var infras infrastructure.Infrastructure
	infs := infras.GetConn()
	id := ledger["project_items_id"]
	delete(ledger, "project_items_id") // 移除主键字段，不参与更新

	ledgerConstruct := constant.Ledger{
		ProjectItemsId:         "",
		TicketYears:            ledger["ticket_years"].(string),
		ProjectManager:         ledger["project_manager"].(string),
		ProjectRoleA:           ledger["project_role_a"].(string),
		OfficialManager:        ledger["official_manager"].(string),
		TicketInfo:             ledger["ticket_info"].(string),
		ProjectStatus:          ledger["project_status"].(string),
		ProgressStream:         ledger["progress_stream"].(string),
		ExpectDeployTime:       ledger["expect_deploy_time"].(string),
		ProjectReplyOnlineTime: ledger["project_reply_online_time"].(string),
		ServerInfo: constant.ServerInfo{
			ServerType:      ledger["server_type"].(string),
			ServerStructure: ledger["server_structure"].(string),
			OsName:          ledger["os_name"].(string),
			CpuStructure:    ledger["cpu_structure"].(string),
			CpuInfo:         ledger["cpu_info"].(string),
			CpuCoreCount:    ledger["cpu_core_count"].(string),
			OsPlantform:     ledger["os_plantform"].(string),
			OsVersion:       ledger["os_version"].(string),
			OsCoreVersion:   ledger["os_core_version"].(string),
			MemoryInfo:      ledger["memory_info"].(string),
			DiskInfo:        ledger["disk_info"].(string),
			Structure:       ledger["structure"].(string),
			ClusterName:     ledger["cluster_name"].(string),
			HostName:        ledger["host_name"].(string),
			Domain:          ledger["domain"].(string),
			Pod:             ledger["pod"].(string),
		},
		DatabaseInfo: constant.DatabaseInfo{
			DataVolume:       ledger["data_volume"].(string),
			DbType:           ledger["db_type"].(string),
			DbVersion:        ledger["db_version"].(string),
			CompatibleModel:  ledger["compatible_model"].(string),
			DbIp:             ledger["db_ip"].(string),
			DbVip:            ledger["db_vip"].(string),
			DbPort:           ledger["db_port"].(string),
			DbDataPath:       ledger["db_data_path"].(string),
			DbArchivePath:    ledger["db_archive_path"].(string),
			DbBackupPath:     ledger["db_backup_path"].(string),
			DbBackupStrategy: ledger["db_backup_strategy"].(string),
			Monitor:          ledger["monitor"].(string),
		},
		Env:                     ledger["env"].(string),
		ServerHandover:          ledger["server_handover"].(string),
		Migrate:                 ledger["migrate"].(string),
		ExpectOnlineTime:        ledger["expect_online_time"].(string),
		BelongCompany:           ledger["belong_company"].(string),
		BelongApartment:         ledger["belong_apartment"].(string),
		BelongBusiness:          ledger["belong_business"].(string),
		SubSystemName:           ledger["sub_system_name"].(string),
		BussinessLevel:          ledger["bussiness_level"].(string),
		MainUses:                ledger["main_uses"].(string),
		ProjectBussinessManager: ledger["project_bussiness_manager"].(string),
		ContactPhoneNumber:      ledger["contact_phone_number"].(string),
		LoginType:               ledger["login_type"].(string),
		UserAndPasswd:           ledger["user_and_passwd"].(string),
		Remarks:                 ledger["remarks"].(string),
	}
	ledgerConstruct.ProjectItemsId = id.(string)

	err := infs.SaveOrUpdateDynamic(&ledgerConstruct, []string{"project_items_id"}, ledger)
	if err != nil {
		log.Println(err)
		return err
	}
	err = infs.Close()
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

// 上传文件
func (pj *Projects) UploadFiles(c *gin.Context) ([]string, error) {

	// 检查目录是否存在
	if _, err := os.Stat(getDeployConfirmFormPath()); os.IsNotExist(err) {
		fmt.Println("目录不存在:", getDeployConfirmFormPath())
		return nil, err
	}

	// 获取上传的文件
	form, err := c.MultipartForm()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "获取上传文件失败"})
		return nil, err
	}
	files := form.File["files"]

	// 处理每个文件
	var uploadedFiles []string
	for _, file := range files {
		// 生成唯一文件名
		ext := filepath.Ext(file.Filename)
		filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
		filePath := filepath.Join(getDeployConfirmFormPath(), filename)

		// 保存文件
		if err := c.SaveUploadedFile(file, filePath); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "保存文件失败"})
			return nil, err
		}

		uploadedFiles = append(uploadedFiles, file.Filename)
	}
	return uploadedFiles, nil
}

func (pj *Projects) StructureLedgerHeaders(headerRows []interface{}) ([]constant.Header, error) {
	var headers []constant.Header

	for _, row := range headerRows {
		cols, ok := row.([]interface{})
		if !ok || len(cols) < 2 {
			continue // 跳过异常行
		}

		label, _ := cols[1].(string)
		columnName, _ := cols[0].(string)
		//h := map[string]string{
		//	"label": label,
		//	"key": toCamelCase(columnName),
		//}

		header := constant.Header{
			Label: label,
			Key:   columnName,
		}
		headers = append(headers, header)
	}
	return headers, nil
}

func (pj *Projects) StructureLedgerDatas(headerRows []interface{}) ([]constant.Ledger, error) {
	var ledgers []constant.Ledger

	for _, row := range headerRows {
		cols, ok := row.([]interface{})
		if !ok || len(cols) < 2 {
			continue // 跳过异常行
		}

		TicketYears, _ := cols[0].(string)
		ProjectManager, _ := cols[1].(string)
		ProjectRoleA, _ := cols[2].(string)
		OfficialManager, _ := cols[3].(string)
		TicketInfo, _ := cols[4].(string)
		ProjectStatus, _ := cols[5].(string)
		ProgressStream, _ := cols[6].(string)
		ExpectDeployTime, _ := cols[7].(string)
		ProjectReplyOnlineTime, _ := cols[8].(string)
		ServerType, _ := cols[9].(string)
		ServerStructure, _ := cols[10].(string)
		OsName, _ := cols[11].(string)
		CpuStructure, _ := cols[12].(string)
		CpuInfo, _ := cols[13].(string)
		CpuCoreCount, _ := cols[14].(string)
		OsPlantform, _ := cols[15].(string)
		OsVersion, _ := cols[16].(string)
		OsCoreVersion, _ := cols[17].(string)
		MemoryInfo, _ := cols[18].(string)
		DiskInfo, _ := cols[19].(string)
		Structure, _ := cols[20].(string)
		ClusterName, _ := cols[21].(string)
		HostName, _ := cols[22].(string)
		Domain, _ := cols[23].(string)
		Pod, _ := cols[24].(string)
		DataVolume, _ := cols[25].(string)
		DbType, _ := cols[26].(string)
		DbVersion, _ := cols[27].(string)
		CompatibleModel, _ := cols[28].(string)
		DbIp, _ := cols[29].(string)
		DbVip, _ := cols[30].(string)
		DbPort, _ := cols[31].(string)
		DbDataPath, _ := cols[32].(string)
		DbArchivePath, _ := cols[33].(string)
		DbBackupPath, _ := cols[34].(string)
		DbBackupStrategy, _ := cols[35].(string)
		Monitor, _ := cols[36].(string)
		Env, _ := cols[37].(string)
		ServerHandover, _ := cols[38].(string)
		Migrate, _ := cols[39].(string)
		ExpectOnlineTime, _ := cols[40].(string)
		BelongCompany, _ := cols[41].(string)
		BelongApartment, _ := cols[42].(string)
		BelongBusiness, _ := cols[43].(string)
		SubSystemName, _ := cols[44].(string)
		BussinessLevel, _ := cols[45].(string)
		MainUses, _ := cols[46].(string)
		ProjectBussinessManager, _ := cols[47].(string)
		ContactPhoneNumber, _ := cols[48].(string)
		LoginType, _ := cols[49].(string)
		UserAndPasswd, _ := cols[50].(string)
		Remarks, _ := cols[51].(string)
		ProjectItemsId, _ := cols[52].(string)

		ledger := constant.Ledger{
			ProjectItemsId:         ProjectItemsId,
			TicketYears:            TicketYears,
			ProjectManager:         ProjectManager,
			ProjectRoleA:           ProjectRoleA,
			OfficialManager:        OfficialManager,
			TicketInfo:             TicketInfo,
			ProjectStatus:          ProjectStatus,
			ProgressStream:         ProgressStream,
			ExpectDeployTime:       ExpectDeployTime,
			ProjectReplyOnlineTime: ProjectReplyOnlineTime,
			ServerInfo: constant.ServerInfo{
				ServerType:      ServerType,
				ServerStructure: ServerStructure,
				OsName:          OsName,
				CpuStructure:    CpuStructure,
				CpuInfo:         CpuInfo,
				CpuCoreCount:    CpuCoreCount,
				OsPlantform:     OsPlantform,
				OsVersion:       OsVersion,
				OsCoreVersion:   OsCoreVersion,
				MemoryInfo:      MemoryInfo,
				DiskInfo:        DiskInfo,
				Structure:       Structure,
				ClusterName:     ClusterName,
				HostName:        HostName,
				Domain:          Domain,
				Pod:             Pod,
			},
			DatabaseInfo: constant.DatabaseInfo{
				DataVolume:       DataVolume,
				DbType:           DbType,
				DbVersion:        DbVersion,
				CompatibleModel:  CompatibleModel,
				DbIp:             DbIp,
				DbVip:            DbVip,
				DbPort:           DbPort,
				DbDataPath:       DbDataPath,
				DbArchivePath:    DbArchivePath,
				DbBackupPath:     DbBackupPath,
				DbBackupStrategy: DbBackupStrategy,
				Monitor:          Monitor,
			},
			Env:                     Env,
			ServerHandover:          ServerHandover,
			Migrate:                 Migrate,
			ExpectOnlineTime:        ExpectOnlineTime,
			BelongCompany:           BelongCompany,
			BelongApartment:         BelongApartment,
			BelongBusiness:          BelongBusiness,
			SubSystemName:           SubSystemName,
			BussinessLevel:          BussinessLevel,
			MainUses:                MainUses,
			ProjectBussinessManager: ProjectBussinessManager,
			ContactPhoneNumber:      ContactPhoneNumber,
			LoginType:               LoginType,
			UserAndPasswd:           UserAndPasswd,
			Remarks:                 Remarks,
		}
		ledgers = append(ledgers, ledger)
	}
	return ledgers, nil
}

func (pj *Projects) DownloadFiles(c *gin.Context) {
	//files, err := getFileList(uploadDir)
	//if err != nil {
	//	c.JSON(http.StatusInternalServerError, gin.H{"error": "获取文件列表失败"})
	//	return
	//}
}

// 获取磐维交付确认单路径
func getDeployConfirmFormPath() string {
	currentDir, err := os.Getwd()
	if err != nil {
		return ""
	}

	// 获取上级目录
	parentDir := filepath.Dir(currentDir)

	// 构建files目录路径
	filesDir := filepath.Join(parentDir, "files")

	// 检查目录是否存在
	if _, err := os.Stat(filesDir); os.IsNotExist(err) {
		err := os.Mkdir(filesDir, 0755)
		if err != nil {
			return ""
		}
	}

	return filesDir
}
